package informationplatform.overtime

import informationplatform.UserGroup;
import informationplatform.hibernate.CurrentUser;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook
import org.apache.poi.ss.usermodel.Cell
import org.apache.poi.ss.usermodel.CellStyle
import org.apache.poi.ss.usermodel.Font
import org.apache.poi.ss.usermodel.IndexedColors
import org.apache.poi.ss.usermodel.Row
import org.apache.poi.ss.usermodel.Sheet
import org.apache.poi.ss.usermodel.Workbook
import org.apache.poi.ss.util.CellRangeAddress
import java.util.ArrayList;
import java.util.List;

class OvertimeService {
	static transactional = true
	def sftime= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

	def start(applicant) {
		def overtime = new Overtime();

		overtime.punchStartClockTime = Calendar.getInstance().getTime()
		overtime.type = OvertimeType.IMMEDIATE
		overtime.applicant = applicant

		overtime.save()
		return overtime
	}

	def saveEnd(overtimeDto) {
		def overtimes = Overtime.withCriteria {
			eq('createdBy', CurrentUser.name)
			isNotNull('punchStartClockTime')
			isNull('punchEndClockTime')
		}

		def overtime = overtimes[0]

		overtime.punchEndClockTime = Calendar.getInstance().getTime()
		overtime.project=overtimeDto.project
		overtime.reason = overtimeDto.reason

		if(overtimeDto.haveTaxi){
			overtime.haveTaxi =Boolean.valueOf(overtimeDto.haveTaxi)
		}

		if(overtimeDto.taxiPrice){
			overtime.taxiPrice = Float.valueOf(overtimeDto.taxiPrice)
		}
		overtime.status = OvertimeStatus.VALID
		overtime.ip = overtimeDto.ip
		
		overtime.save()
		
		if(!Boolean.valueOf(overtimeDto.haveDeal)){
			overtime.overtimeMeals*.delete()
		}
		
		return overtime
	}

	def save(overtimeDto) {
		def overtime = Overtime.get(overtimeDto.id)

		overtime.project=overtimeDto.project
		overtime.reason = overtimeDto.reason

		if(overtimeDto.haveTaxi){
			overtime.haveTaxi =Boolean.valueOf(overtimeDto.haveTaxi)
		}
		if(overtimeDto.taxiPrice){
			overtime.taxiPrice = Float.valueOf(overtimeDto.taxiPrice)
		}else{
			overtime.taxiPrice =0.0f
		}

		overtime.save()
		if(!Boolean.valueOf(overtimeDto.haveDeal)){
			overtime.overtimeMeals*.delete()
		}
		
		return overtime
	}

	def saveSupplement(overtimeDto,applicant) {
		def overtime = new Overtime();

		overtime.punchStartClockTime = sftime.parse(overtimeDto.punchStartClockTime)
		overtime.punchEndClockTime = sftime.parse(overtimeDto.punchEndClockTime)

		overtime.type = OvertimeType.SUPPLEMENT
		overtime.status = OvertimeStatus.NO_VALID
		overtime.statusCauses ="事后补加班"

		overtime.project = overtimeDto.project
		overtime.reason = overtimeDto.reason
		overtime.applicant = applicant

		if(overtimeDto.haveTaxi){
			overtime.haveTaxi =Boolean.valueOf(overtimeDto.haveTaxi)
		}
		if(overtimeDto.taxiPrice){
			overtime.taxiPrice = Float.valueOf(overtimeDto.taxiPrice)
		}

		overtime.save()
		return overtime
	}

	// -----------------------------------------------------------------------------统计计算
	def stastic(List<Overtime> overtimeList){
		def groupOvertimeMap = [:]

		overtimeList.each{
			GroupOvertime groupOvertime
			PersonOvertime personOvertime

			// 1. 取group overtime
			if(groupOvertimeMap.containsKey(it.applicant.group)){
				groupOvertime = groupOvertimeMap.get(it.applicant.group)
			}else{

				groupOvertime = new GroupOvertime()
				groupOvertimeMap.put(it.applicant.group, groupOvertime)
			}

			// 2. 取person overtime
			if(groupOvertime.personOvertimeMap.containsKey(it.applicant)){
				personOvertime =groupOvertime.personOvertimeMap.get(it.applicant)
			}else{

				personOvertime = new PersonOvertime()
				groupOvertime.personOvertimeMap.put(it.applicant, personOvertime)
			}

			//3. 累加工时
			def workingHour=0.0f
			if(it.punchEndClockTime && it.punchStartClockTime){
				workingHour = new BigDecimal((it.punchEndClockTime.getTime() - it.punchStartClockTime.getTime())/ (1000 * 60 * 60f)).setScale(1, BigDecimal.ROUND_HALF_UP).toFloat()
			}
			personOvertime.hoursTotal += workingHour

			//4. 累加用餐
			def overtime = it
			def meals = OvertimeMeal.withCriteria { eq('overtime',overtime) }
			meals.each{
				if(it.payway == MealPayway.TEAM_CARD){
					personOvertime.mealTeamCardConsumeTotal += it.price

				}else if(it.payway == MealPayway.SELF_CARD){
					personOvertime.mealSelfCardConsumeTotal += it.price
				}
			}

			//5. 打的次数
			if(overtime.haveTaxi){
				personOvertime.taxiCnt += 1
			}
		}

		//5. group 总计结果
		groupOvertimeMap.each{group, groupOvertime->

			groupOvertime.personOvertimeMap.each{applicant, personOvertime ->
				groupOvertime.hoursTotal += personOvertime.hoursTotal
				groupOvertime.mealTeamCardConsumeTotal += personOvertime.mealTeamCardConsumeTotal
			}
		}

		return groupOvertimeMap
	}



	// -----------------------------------------------------------------------------统计excel导出
	def exportExcel(Map<UserGroup,GroupOvertime> groupOvertimeMap){
		//创建excel内容
		Workbook wb = new HSSFWorkbook()

		//------------------------------------------------------------表头表格样式
		CellStyle headStyle = wb.createCellStyle()
		Font font = wb.createFont()
		font.setFontHeightInPoints((short)10)
		font.setBoldweight(Font.BOLDWEIGHT_BOLD)
		headStyle.setFont(font)
		headStyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex())
		headStyle.setFillPattern(CellStyle.SOLID_FOREGROUND)
		headStyle.setBorderBottom(CellStyle.BORDER_THIN)
		headStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex())
		headStyle.setBorderLeft(CellStyle.BORDER_THIN)
		headStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex())
		headStyle.setBorderRight(CellStyle.BORDER_THIN)
		headStyle.setRightBorderColor(IndexedColors.BLACK.getIndex())
		headStyle.setBorderTop(CellStyle.BORDER_THIN)
		headStyle.setTopBorderColor(IndexedColors.BLACK.getIndex())
		//内容表格样式
		CellStyle dataStyle = wb.createCellStyle()
		dataStyle.setBorderBottom(CellStyle.BORDER_THIN)
		dataStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex())
		dataStyle.setBorderLeft(CellStyle.BORDER_THIN)
		dataStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex())
		dataStyle.setBorderRight(CellStyle.BORDER_THIN)
		dataStyle.setRightBorderColor(IndexedColors.BLACK.getIndex())
		dataStyle.setBorderTop(CellStyle.BORDER_THIN)
		dataStyle.setTopBorderColor(IndexedColors.BLACK.getIndex())
		dataStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER)
		//隔开行填充色样式
		CellStyle groupStyle = wb.createCellStyle()
		groupStyle.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex())
		groupStyle.setFillPattern(CellStyle.SOLID_FOREGROUND)
		groupStyle.setBorderBottom(CellStyle.BORDER_THIN)
		groupStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex())
		groupStyle.setBorderLeft(CellStyle.BORDER_THIN)
		groupStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex())
		groupStyle.setBorderRight(CellStyle.BORDER_THIN)
		groupStyle.setRightBorderColor(IndexedColors.BLACK.getIndex())
		groupStyle.setBorderTop(CellStyle.BORDER_THIN)
		groupStyle.setTopBorderColor(IndexedColors.BLACK.getIndex())


		Sheet sheet1 = wb.createSheet("个人统计")
		//------------------------------------------------表头
		short rowNm = 0
		Row row = sheet1.createRow(rowNm ++ )
		row.setHeight((short) 15.625 * 30)

		Cell cell = row.createCell(0)
		cell.setCellValue('项目组')
		cell.setCellStyle(headStyle)

		cell = row.createCell(1)
		cell.setCellValue('加班人')
		cell.setCellStyle(headStyle)

		cell = row.createCell(2)
		cell.setCellValue('加班时间总计(小时)')
		cell.setCellStyle(headStyle)

		cell = row.createCell(3)
		cell.setCellValue('用餐使用自己工卡总计(元)')
		cell.setCellStyle(headStyle)

		cell = row.createCell(4)
		cell.setCellValue('用餐使用专项卡总计(元)')
		cell.setCellStyle(headStyle)
		
		cell = row.createCell(5)
		cell.setCellValue('打的次数')
		cell.setCellStyle(headStyle)


		//-----------------------------------------------查出结果集

		//-----------------------------------------------打印内容
		groupOvertimeMap.each{group, groupOvertime->
			groupOvertime.personOvertimeMap.each{applicant, personOvertime ->
				row = sheet1.createRow(rowNm ++ )
				//0
				cell = row.createCell(0)
				cell.setCellStyle(dataStyle)
				cell.setCellValue(group.name)
				//1
				cell = row.createCell(1)
				cell.setCellStyle(dataStyle)
				cell.setCellValue(applicant.realName)
				//2
				cell = row.createCell(2)
				cell.setCellStyle(dataStyle)
				cell.setCellValue(String.format("%.1f", personOvertime.hoursTotal))
				//3
				cell = row.createCell(3)
				cell.setCellStyle(dataStyle)
				cell.setCellValue(String.format("%.1f", personOvertime.mealSelfCardConsumeTotal))
				//4
				cell = row.createCell(4)
				cell.setCellStyle(dataStyle)
				cell.setCellValue(String.format("%.1f", personOvertime.mealTeamCardConsumeTotal))
				
				//5
				cell = row.createCell(5)
				cell.setCellStyle(dataStyle)
				cell.setCellValue(personOvertime.taxiCnt)
			}
		}

		sheet1.setColumnWidth((short) 0,(short) 30*256);
		sheet1.setColumnWidth((short) 1,(short) 10*256);
		sheet1.setColumnWidth((short) 2,(short) 20*256);
		sheet1.setColumnWidth((short) 3,(short) 25*256);
		sheet1.setColumnWidth((short) 4,(short) 25*256);

		//--------------------------------------------------------------------------个人统计和专项统计分界线
		Sheet sheet2 = wb.createSheet("专项统计")
		//------------------------------------------------表头
		rowNm = 0
		row = sheet2.createRow(rowNm ++ )
		row.setHeight((short) 15.625 * 30)

		cell = row.createCell(0)
		cell.setCellValue('项目组')
		cell.setCellStyle(headStyle)

		cell = row.createCell(1)
		cell.setCellValue('加班时间总计(小时)')
		cell.setCellStyle(headStyle)

		cell = row.createCell(2)
		cell.setCellValue('用餐使用专项卡总计(元)')
		cell.setCellStyle(headStyle)


		//-----------------------------------------------查出结果集

		//-----------------------------------------------打印内容
		groupOvertimeMap.each{group, groupOvertime->
			row = sheet2.createRow(rowNm ++ )
			//0
			cell = row.createCell(0)
			cell.setCellStyle(groupStyle)
			cell.setCellValue(group.name + "总计:")
			//2
			cell = row.createCell(1)
			cell.setCellStyle(groupStyle)
			cell.setCellValue(String.format("%.1f", groupOvertime.hoursTotal))
			//4
			cell = row.createCell(2)
			cell.setCellStyle(groupStyle)
			cell.setCellValue(String.format("%.1f", groupOvertime.mealTeamCardConsumeTotal))
		}

		sheet2.setColumnWidth((short) 0,(short) 30*256);
		sheet2.setColumnWidth((short) 1,(short) 20*256);
		sheet2.setColumnWidth((short) 2,(short) 25*256);

		return wb
	}
}
